<template>
  <div class="dashboard-card" style="padding: 20px;">
    <div class="card-header">
      <h3>项目列表</h3>
      <el-button type="primary" @click="showAddDialog"><el-icon><Plus /></el-icon> 添加</el-button>
    </div>
    <el-table :data="items" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="name" label="项目名" width="200" />
      <el-table-column prop="code" label="项目代码" width="150" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="editItem(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteItem(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑' : '添加'" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="项目名"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="项目代码"><el-input v-model="form.code" /></el-form-item>
        <el-form-item label="描述"><el-input v-model="form.description" type="textarea" :rows="3" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { projectAPI } from '@/api'

const items = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref({ name: '', code: '', description: '' })

const fetchItems = async () => {
  const data = await projectAPI.list()
  items.value = data.results || data
}

const showAddDialog = () => {
  isEdit.value = false
  form.value = { name: '', code: '', description: '' }
  dialogVisible.value = true
}

const editItem = (item) => {
  isEdit.value = true
  form.value = { ...item }
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    if (isEdit.value) {
      await projectAPI.update(form.value.id, form.value)
    } else {
      await projectAPI.create(form.value)
    }
    ElMessage.success('操作成功')
    dialogVisible.value = false
    fetchItems()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteItem = (item) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await projectAPI.delete(item.id)
    ElMessage.success('删除成功')
    fetchItems()
  })
}

onMounted(fetchItems)
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-header h3 {
  margin: 0;
  color: #3a84ff;
  font-size: 20px;
}
</style>
